package com.lxf.clouduser.utils;

import lombok.Data;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;

/**
 * @author 罗兴发
 * @data 2025/9/25 10:12
 * @description：验证码工具类---用于生成图片验证码
 */
@Component
public class CaptchaUtils {
    /**
     * 随机生出表达式和答案
     * 用于生成图片验证码
     * @return
     */
    public static MathExpression generateMathExpression(){
        Random random = new Random();
        int a = random.nextInt(10)+1;// 1-10的随机数
        int b = random.nextInt(10)+1;// 1-10的随机数

        // 随机确定加/减法
        String operator;
        int result;
        if (random.nextBoolean()){
            operator = "+";
            result = a+b;
        }else {
            operator = "-";
            // 保证差值不能为负数
            if (a<b){
                // 作一个值交换
                int temp = a;
                a = b;
                b = temp;
            }
            result = a-b;
        }
        String expression = a+""+operator+""+b+"=?";
        return new MathExpression(expression,result);
    }


    public static String generateCaptchaImage(String expression)throws IOException {
        int width = 120;//宽
        int height = 40;//高

        // 创建图片对象
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        // 创建2D图片
        Graphics2D g = image.createGraphics();

        // 设置背景颜色
        g.setColor(Color.white);
        g.fillRect(0,0,width,height);

        // 设置字体
        g.setFont(new Font("Arial",Font.BOLD,16));

        // 绘制干扰线,避免被恶意攻击（避免电脑自动识别）
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
            g.drawLine(x1,y1,x2,y2);
        }

        // 绘制表达式文字
        g.setColor(Color.BLACK);
        g.drawString(expression,10,25);

        g.dispose();

        // 将图片转为Base64字符串
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image,"png",baos);
        byte[] bytes = baos.toByteArray();

        return "data:image/png;base64,"+ Base64.getEncoder().encodeToString(bytes);

    }


    /**
     * 用于存储表达式和结果
     */
    @Data
    public static class MathExpression{
        private String expression;
        private int result;

        // 构造
        public MathExpression(String expression,int result){
            this.expression = expression;
            this.result = result;
        }
    }
}
